
import '../lib/jquery.js'
import {ajax} from '../utils/ajax.js'

//商品的筛选
let listBox = $('.list'); 
let categoryBox = $('.category');  
let filterBox = $('.filterBox').first();  
let saleBox = $('.saleBox');  
let sortBox = $('.sortBox');  
let searchBox = $('.search');  

//页数的操作
let firstBtn = $('.first');
let prevBtn = $('.prev');
let nextBtn = $('.next');
let lastBtn = $('.last');
let totalBox = $('.total');  
let pagesizeBox = $('.pagesize');  
let jumpBox = $('.jump');  
let jumpBtn = $('.go');  
let totalPage;  

//请求发送的数据
let data = {
    current: 1, 
    pagesize: 12,  
    search: '',  
    filter: '',  
    saleType: 10,  
    sortType: 'id',  
    sortMethod: 'ASC',  
    category: '',  
}

//分类列表
async function renderCategory(){

    //请求 category 获取分类列表
    let classify = await ajax.get('/goods/category');
    let {code, list} = classify.data;
    if (code != 1) return console.log('获取分类列表失败');
    let str = `<li class="active">全部</li>`;

    //遍历分类列表添加
    for (let i = 1; i < list.length; i++) str += `<li>${list[i]}</li>`;
    str += `<li>其他</li>`;

    //渲染到页面上
    categoryBox.html(str);
}
renderCategory();

//商品列表
async function renderList() {

    //发送 data，请求商品列表
    let goods = await ajax.get('/goods/list', {params: data});
    let  {code, list, total} = goods.data;
    if (code != 1) return console.log('获取商品列表失败');

    //渲染列表
    let str = ``;
    list.forEach(e => {
        str += `<li data-id="${e.goods_id}">
                    <div class="show">
                        <img src="${e.img_big_logo}">
                        ${e.is_hot ? '<span class="hot">热销</span>' : ''}
                        ${e.is_sale ? '<span>折扣</span>' : ''}
                    </div>
                    <div class="info">
                        <p class="title">${e.title}</p>
                        <p class="price">
                            <span class="curr">¥ ${e.current_price}</span>
                            <span class="old">¥ ${e.price}</span>
                        </p>        
                    </div>
                </li>`
    })

    //没有时显示 nothing 图片，并且页数全是 0
    if (list.length == 0) {
        data.current = 0;
        str = '<img src="../img/no.png" alt="">';
    }
    listBox.html(str);

    // 当前页 / 总页数
    totalPage = total;
    totalBox.text(`${data.current} / ${totalPage}`);

    //跳转改为当前页
    jumpBox.val(`${data.current}`);

    //首页，末页，上一页，下一页全部设置成能按
    prevBtn.removeClass('disable');
    nextBtn.removeClass('disable');
    firstBtn.removeClass('disable');
    lastBtn.removeClass('disable');

    //再判断当前页在哪， <= 1 首页跟上一页就不能按
    if (data.current <= 1) {
        prevBtn.addClass('disable');
        firstBtn.addClass('disable');
    }

    // == 总页数（最后一页） 下一页跟末页就不能按
    if (data.current == totalPage) {
        nextBtn.addClass('disable');
        lastBtn.addClass('disable');
    }
}
renderList();

//分类
categoryBox.on('click', ({target}) => {

    //如果点击的是 <li>
    if (target.nodeName == 'LI') {

        //所有 <li> 去除 active 
        categoryBox.children().removeClass('active');

        //点击的那个 li 加上 active
        target.classList.add('active');

        //获取点击的文本，空就是全部
        let str = target.innerText;
        if (str == '全部') str = '';

        //修改 data 的 category 属性
        data.category = str;
        renderList();
    }
})

//首页 末页
firstBtn.on('click', () => {

    //当前页设为 1
    data.current = 1;
    renderList();
})
lastBtn.on('click', () => {
    data.current = totalPage;
    renderList();
})

//上一页 下一页
prevBtn.on('click', () => {
    if (data.current > 1){
     data.current--;
    renderList();
    }
})
nextBtn.on('click', () => {
    if (data.current < totalPage){
    data.current++;
    renderList();
    }
})

//跳转
jumpBtn.on('click', () => {

    //获取跳转页的值
    let target = jumpBox.val();

    //判断是否可以跳转
    if (target < 1 || target > totalPage){
    return alert('跳转页不存在');
    }

    //将当前页标为要跳转的页数
    data.current = target;
    renderList();

})

//一页显示几条
pagesizeBox.on('change', () => {

    //获取值
    data.pagesize = pagesizeBox.val();

    //修改一页个数 -> 总页数减少 -> 可能当前页会超出总页数
    data.current = 1;
    renderList();
})

// 热销/折扣
filterBox.on('click', ({target}) => {
    if (target.nodeName == 'LI') {

        //把 li 的 active 豆沙了
        filterBox.children().removeClass('active');

        //当前点击的 li 添加 active
        target.classList.add('active');

        //获取分类类型
        data.filter = target.dataset.type;

        //总页数可能会减少，导致当前页超出总页数，所以直接标为 1
        data.current = 1;
        renderList();
    }
})

//几折
saleBox.on('click', ({target}) => {
    
    //跟上面一样的
    if (target.nodeName == 'LI') {
        saleBox.children().removeClass('active');
        target.classList.add('active');
        data.saleType = target.dataset.type;
        data.current = 1;
        renderList();
    }
})

//对id、折扣、价格进行排序（正序、倒序）
sortBox.on('click', ({target}) => {
    if (target.nodeName == 'LI') {
        sortBox.children().removeClass('active');
        target.classList.add('active');
        data.sortType = target.dataset.type;

        data.sortMethod = target.dataset.method;
        data.current = 1;
        renderList();
    }
})

//搜索，节流处理
let flag = false;
searchBox.on('input', () => {

    // cd 还没到，return
    if (flag) retrun;

    //标记当前 cd
    flag = true;

    //定时器，500ms 后 cd 到了
    setTimeout(() => {

        //获取搜索框的值
        data.search = searchBox.val().trim();
        data.current = 1; 
        renderList();

        //标记 cd 
        flag = false;
    }, 500);
})

//商品详情
listBox.on('click', ({target}) => {
    if (target.nodeName == 'LI') {

        //获取点击的商品的 id
        let id = target.dataset.id;

        //存在会话里面
        sessionStorage.setItem('id', id);
        
        //跳转到详情页
        location.href = './detail.html';
    }
})